using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Xml.Linq;

namespace MESTest
{
    public partial class MainWindow : Window
    {
        private List<DataItem> allData = new List<DataItem>();
        private int currentPage = 0;
        private const int itemsPerPage = 16;
        private DispatcherTimer timer;
        private Random random = new Random();

        public MainWindow()
        {
            InitializeComponent();
            InitializeData();
            UpdateDisplay();
            InitializeTimer();
            timer.Start();
        }

        private void InitializeData()
        {
            try
            {
                if (!File.Exists("config1.xml"))
                {
                    CreateDefaultConfig();
                }
                
                XDocument doc = XDocument.Load("config1.xml");
                int i = 1;
                foreach (var item in doc.Descendants("DataItem"))
                {
                    allData.Add(new DataItem
                    {
                        Name = item.Attribute("Name").Value,
                        Value = random.Next(1, 100),
                        Unit = item.Attribute("Unit").Value
                    });
                    i++;
                }
            }
            catch
            {
                // 如果配置文件加载失败，使用默认值
                for (int i = 1; i <= 80; i++)
                {
                    allData.Add(new DataItem
                    {
                        Name = "数据" + i,
                        Value = random.Next(1, 100),
                        Unit = "单位" + (i % 5 + 1)
                    });
                }
            }
        }
        
        private void CreateDefaultConfig()
        {
            string[] names = {
                "1#发电网电功率", "2#发电网电功率", "3#发电网电功率", "4#发电网电功率", "5#发电网电功率",
                "1#A泥浆泵功率", "1#B泥浆泵功率", "2#A泥浆泵功率", "2#B泥浆泵功率", "3#A泥浆泵功率",
                "3#B泥浆泵功率", "A绞车功率", "B绞车功率", "转盘功率", "顶驱功率",
                "1#固控区供电功率", "2#固控区供电功率", "3#固控区供电功率", "4#固控区供电功率", "5#固控区供电功率",
                "6#固控区供电功率", "7#固控区供电功率", "8#固控区供电功率", "9#固控区供电功率", "10#固控区供电功率",
                "11#固控区供电功率", "1#加重泵功率", "2#加重泵功率", "3#加重泵功率", "4#加重泵功率",
                "5#加重泵功率", "1#灌注泵功率", "2#灌注泵功率", "3#灌注泵功率", "1#快速加重功率",
                "2#快速加重功率", "3#快速加重功率", "除砂泵功率", "除泥泵功率", "剪切泵功率",
                "变频离心机功率", "辅助用电功率", "生活区1用电功率", "生活区2用电功率", "井场营房用电功率",
                "大钩负荷", "钻压", "大钩高度", "钻头位置", "井深",
                "游车速度", "钻时", "顶驱转速", "顶驱扭矩", "转盘转速",
                "转盘扭矩", "泵压", "泵速1", "泵速2", "泵速3",
                "泵排量1", "泵排量2", "泵排量3", "每米总能耗", "绞车能耗",
                "MP1能耗", "MP2能耗", "MP3能耗", "RT能耗", "TD能耗",
                "固控区能耗", "泵区辅助能耗", "其他辅助能耗"
            };
            
            string[] units = {
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kW",
                "kW", "kW", "kW", "kW", "kN",
                "kN", "m", "m", "m", "m/s",
                "min/m", "rpm", "kN.m", "rpm", "kN.m",
                "MPa", "spm", "spm", "spm", "lpm",
                "lpm", "lpm", "kWh/m", "kWh", "kWh",
                "kWh", "kWh", "kWh", "kWh", "kWh",
                "kWh", "kWh"
            };
            
            XDocument doc = new XDocument(
                new XElement("DataItems",
                    Enumerable.Range(0, 80).Select(i => 
                        new XElement("DataItem",
                            new XAttribute("Name", names[i]),
                            new XAttribute("Unit", units[i])
                        )
                    )
                )
            );
            doc.Save("config1.xml");
        }

        private void InitializeTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("[DEBUG] 开始Timer_Tick");

            foreach (var item in allData)
            {
                item.Value = random.Next(0, 100);
            }
            UpdateDisplay();
            
            // 更新图表数据
            if (ChartContainer.ItemsSource == null)
            {
                ChartContainer.ItemsSource = Enumerable.Range(0, 8).ToList();
            }
            
            // 获取当前显示的数据
            var displayData = DataGrid.ItemsSource as IList<DataItem>;
            if (displayData == null) return;

            AllChartValues.Text = "123" + "4656";

            foreach (var (chart, index) in ChartContainer.Items.OfType<DoubleLineChart>().Select((c, i) => (c, i)))
            {
                //AllChartValues.Text = 
                if (displayData.Count > index * 2 + 1)
                {
                    AllChartValues.Text = AllChartValues.Text + index.ToString();
                    // 使用顶部同一列的2个数据值更新曲线
                    chart.AddDataPoint(displayData[index * 2].Value, displayData[index * 2 + 1].Value);
                    
                    // 更新底部显示的数值
                    Dispatcher.Invoke(() => {
                        System.Diagnostics.Debug.WriteLine("[DEBUG] 开始更新AllChartValues控件文本");
                        var values = new StringBuilder();
                        for (int i = 0; i < ChartContainer.Items.Count; i++)
                        {
                            if (displayData.Count > i * 2 + 1)
                            {
                                values.Append($"{i+1}#: {displayData[i * 2].Value:F2}/{displayData[i * 2 + 1].Value:F2}  ");
                            }
                        }
                        string result = values.ToString();
                        System.Diagnostics.Debug.WriteLine($"[DEBUG] 准备更新的文本内容: {result}");
                        System.Diagnostics.Debug.WriteLine($"[DEBUG] 当前控件文本: {AllChartValues.Text}");
                        /* if (AllChartValues.Text != result)
                        {
                            System.Diagnostics.Debug.WriteLine("[DEBUG] 文本内容有变化，执行更新");*/
                            AllChartValues.Text = result;
                            //AllChartValues.InvalidateVisual();
                            //Console.WriteLine("[DEBUG] 更新完成");
                        /* }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("[DEBUG] 文本内容无变化，跳过更新");
                        }*/
                    });
                }
            }
        }

        private void UpdateDisplay()
        {
            int startIndex = currentPage * itemsPerPage;
            int endIndex = Math.Min(startIndex + itemsPerPage, allData.Count);
            
            List<DataItem> displayData = allData.GetRange(startIndex, endIndex - startIndex);
            DataGrid.ItemsSource = displayData;
        }

        private void PrevButton_Click(object sender, RoutedEventArgs e)
        {
            if (currentPage > 0)
            {
                currentPage--;
                UpdateDisplay();
            }
        }

        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            if ((currentPage + 1) * itemsPerPage < allData.Count)
            {
                currentPage++;
                UpdateDisplay();
            }
        }

        private void FirstButton_Click(object sender, RoutedEventArgs e)
        {
            currentPage = 0;
            UpdateDisplay();
        }

        private void LastButton_Click(object sender, RoutedEventArgs e)
        {
            currentPage = (allData.Count - 1) / itemsPerPage;
            UpdateDisplay();
        }

        private void AutoButton_Click(object sender, RoutedEventArgs e)
        {
            if (timer.IsEnabled)
            {
                timer.Stop();
                AutoButton.Content = "自动刷新";
            }
            else
            {
                timer.Start();
                AutoButton.Content = "停止刷新";
            }
        }
    }

    public class DataItem
    {
        public string Name { get; set; }
        public int Value { get; set; }
        public string Unit { get; set; }
    }
}